import time

import jwt
from .common import MD5, error

import logging

logger = logging.getLogger(__name__)

SECRET_KEY = 'olqiz103ppbixad5'
FIXED_HEADER = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.'
ALG = 'HS512'


def jwt_encode(member_id):
    now = int(time.time())
    exp = now + 86400 * 365
    token = jwt.encode({'member_id': member_id, 'exp': exp}, SECRET_KEY, algorithm=ALG)
    token = token.replace(FIXED_HEADER, '')
    return token


def jwt_decode(token):
    member_id = -1
    encoded = FIXED_HEADER + token
    try:
        decode_value = jwt.decode(encoded, SECRET_KEY, algorithms=ALG)
        member_id = decode_value["member_id"]
    except Exception as e:
        logger.error(e.args)
    return member_id


def generate_password(pwd, salt):
    return MD5(pwd + salt)


def check_token(token):
    state = 0
    member_id = jwt_decode(token)
    if member_id == -1:
        return -1, member_id
    return state, member_id


def check_post_request(request):
    return_code = 0
    bodys = {}

    if request.method != 'POST':
        code = 500
        msg = "无法接受post以外的请求"
        return_code = -1
        return return_code, error(msg, errcode=code, data=bodys)

    # 获取token并验证生成member_id
    try:
        token = str(request.headers.get('token'))
        state, member_id = check_token(token)
    except Exception as e:
        logger.info(e.args)
        msg = "token参数错误"
        code = -1
        return_code = -1
        return return_code, error(msg, errcode=code, data=bodys)

    if state == -1:
        msg = "token可能过期"
        code = 110
        return_code = -1
        return return_code, error(msg, errcode=code, data=bodys)

    # TODO 暂不做数据库验证

    return return_code, member_id
